//
//  StatusDAL.swift
//  weibo
//
//  Created by yellow on 15/10/30.
//  Copyright © 2015年 yellow. All rights reserved.
//

import UIKit


/// 定期清理缓存间隔
private var clearDataTime:NSTimeInterval = 7 * 24 * 60 * 60//一周后删除缓存

/// 微博数据访问层，该类会优先从缓存中加载数据，没有就会从网络上获取数据
class StatusDAL: NSObject {

    class func clearCacheData(){
        //确认清除缓存日期
        let date = NSDate(timeIntervalSinceNow: -clearDataTime)
        let dateFormater = NSDateFormatter()
        //一定要设置locale
        dateFormater.locale = NSLocale(localeIdentifier: "en")
        dateFormater.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let dateStr = dateFormater.stringFromDate(date)
        
        
        print("确认清除缓存日期 \(dateStr)")
        
        let sql = "delete from t_status where createTime<?"
        
        FMDBManager.shareManger.queue.inDatabase { (db) -> Void in
            if !db.executeUpdate(sql, dateStr){
                print("删除缓存失败")
            }else{
                print("删除了\(db.changes())条微博缓存")
            }
            
        }
    }
    
    
    // 加载微博数据
    ///
    /// - parameter since_id:    下拉刷新 ID
    /// - parameter max_id:      上拉刷新 ID
    /// - parameter finished:    完成回调
    class func loadData(since_id: Int, max_id: Int,finished: (array: [[String: AnyObject]]?) -> ()){
        let array = checkcacheData(since_id, max_id: max_id)
        if array.count>0{
            print("从缓存加载数据\(array.count)条数据")
            finished(array: array)
        }else{
            print("从网络加载数据")
            
            //如果since_id有值，就会返回比它大得id的微博

            WeiboAPIManager.manager.getCurrentUserAllWeiboFromLast(since_id: since_id, max_id: max_id) { (result, error) -> (Void) in
                
                if error != nil {
                    print("获取用户微博失败,请检查网络状况")
                    finished(array: nil)
                }else{
                    //守卫result有值，且为[String:AnyObject]这种格式的字典
                    guard let dict = result as? [String:AnyObject] else{
                        print("数据格式错误")
                        return
                    }
                    let dictList = dict["statuses"] as! [[String:AnyObject]]
                    
                    //临时数组，用来保存当次获取到的微博list
                    var tempList = [StatusDetailViewModel]()
                    for status in dictList {
                        tempList.append(StatusDetailViewModel(status: Status(dict: status)))
                    }
                    
                    //保存到数据库中
                    saveStatusToDB(dictList)
                    
                    finished(array: dictList)
                }
                
            }
        }
    }
    
}

// MARK: - 私有方法
extension StatusDAL{
    
/// 保存微博数据到数据库中
    private class func saveStatusToDB(dictArray:[[String : AnyObject]]){
        
        guard let uid = UserAccountViewModel.sharedViewModel.account?.uid else{
            print("请登录账号")
            return
        }
        
        //插入新的数据，或者替换为最新的内容
        let sql = "insert or replace into t_status (statusId,status,userId) values(?,?,?);"
            
            FMDBManager.shareManger.queue.inTransaction({ (db, rollback) -> Void in
                
                for dict in dictArray{
                    //  statusId
                    let statusId = dict["id"] as! Int
                    //json格式的status
                    let statusData = try! NSJSONSerialization.dataWithJSONObject(dict, options: [])
                    if !db.executeUpdate(sql,statusId,statusData,uid){
                        print("插入数据失败,\(sql),将进行回滚")
                        rollback.memory = true
                        break
                    }
                }
            })
        
        print("插入数据完毕")
    }
    
    
    /// 检查本地数据
    ///
    /// - parameter since_id: 下拉刷新 id
    /// - parameter max_id:   上拉刷新 id
    ///
    /// - returns: 微博数据的字典数组
    class func checkcacheData(since_id: Int, max_id: Int)->[[String:AnyObject]]{
        
        // 0. 创建数组
        var arrayM = [[String: AnyObject]]()
        
        guard let uid = UserAccountViewModel.sharedViewModel.account?.uid else{
            print("请登录账号")
            return arrayM
        }
        
        //查询微博id为3903787821711230的微博
        var sql = "select * from T_Status where"
        sql += " userId =\(uid)"
        if since_id>0 {
            //下拉
            sql += " and statusId > \(since_id)"
        }else if max_id>0{
            //上啦
            sql += " and statusId < \(max_id)"
        }
        sql += " ORDER BY statusId DESC LIMIT 20;"
        print(sql)
        
        FMDBManager.shareManger.queue.inDatabase { (db) -> Void in
            guard let rs = db.executeQuery(sql)else{
                print("没有查询结果集")
                return
            }
            
            while rs.next(){
                let data = rs.dataForColumn("status")
                let statusDict = try! NSJSONSerialization.JSONObjectWithData(data, options: [])
                arrayM.append(statusDict as! [String : AnyObject])
            }
        }
        
        print("下拉刷新\(since_id),上拉刷新\(max_id)")
        return arrayM
    }
    
}
